/*
 * Copyright 2008-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * XlsFileWriter.java | Created on Sep 29, 2010
 */
package org.gpsoftware.xlsMerge.fileWriter;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.gpsoftware.xlsMerge.Row;
import org.gpsoftware.xlsMerge.WriteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

/**
 * Writes data into an MS Excel file
 *
 * @author Paul Augustine C. Mendoza
 */
class XlsFileWriter implements FileWriter<HSSFRow> {

    private static final String SHEET_NAME = "i18n Keys";

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private File outputFile;

    public void write(File outputFile, Set<Row<HSSFRow>> data) throws
            WriteException {
        this.outputFile = outputFile;
        if (!isValidOutputFile()) {
            throw new IllegalArgumentException("Output cannot be null.");
        }
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(outputFile);
            HSSFWorkbook workbook = createWorkbook(data);
            workbook.write(outputStream);
            logger.info("Data written to " + outputFile.getPath());
        } catch (FileNotFoundException fnfe) {
            throw new WriteException(fnfe, outputFile);
        } catch (IOException ioe) {
            throw new WriteException(ioe, outputFile);
        } catch (Exception e) {
            throw new WriteException(e, outputFile);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ioe) {
                    logger.error(ioe.getMessage(), ioe);
                }
            }
        }
    }

    private boolean isValidOutputFile() {
        return this.outputFile != null;
    }

    private HSSFWorkbook createWorkbook(Set<Row<HSSFRow>> data) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(SHEET_NAME);
        int rowCount = 0;
        HSSFRow oldRow;
        HSSFRow newRow;
        for (Row<HSSFRow> wrappedRow : data) {
            oldRow = wrappedRow.getRowObject();
            newRow = sheet.createRow(rowCount++);
            copyOldRowDataToNewRow(oldRow, newRow);
        }
        return workbook;
    }

    private void copyOldRowDataToNewRow(HSSFRow oldRow, HSSFRow newRow) {
        Iterator iterator = oldRow.iterator();
        int colCount = 0;
        HSSFCell cell;
        while (iterator.hasNext()) {
            cell = (HSSFCell) iterator.next();
            newRow.createCell(colCount++)
                    .setCellValue(cell.getStringCellValue());
        }
    }

    public File getOutputFile() {
        return this.outputFile;
    }
}
